// pages/releaseGoodsPage/releaseGoodsPage.js

const qiniuUploader = require("../common/QNTool/qiniuUploader.js");

// 初始化七牛相关参数
function initQiniu() {
  var options = {
    region: 'ECN',
    uptoken: this.data.qntoken,
    domain: 'http://ohc2uub90.bkt.clouddn.com',
    shouldUseQiniuFileName: false
  };
  qiniuUploader.init(options);
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    qntoken: "",
    // 文字描述
    descContent: "",
    // 图片数组
    photoList: [],
    // 是否显示添加按钮
    isShowAdd: false,
    itemImg_width: 0,
    itemImg_height: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.getServiceQNtoken();
    console.log('页面 传值')
    var photoArray = JSON.parse(options.photoList);
    console.log(photoArray)

    if (photoArray == 9) {
      this.data.isShowAdd = true
    } else {
      this.data.isShowAdd = false
    }
    this.setData({
      isShowAdd: this.data.isShowAdd,
      photoList: photoArray
    })
    this.addPhotoObject();
  },

  /**
   * 获取 七牛上传凭证
   */
  getServiceQNtoken: function (res) {
    var that = this;
    wx.request({
      url: 'https://zhj1214.club/query/qntoken',
      success: function (res) {
        console.log('七牛token  ' + res.data.token);
        that.setData({
          qntoken: res.data.token,
        });
      },
      fail: function (error) {
        console.log(error)
        wx.showToast({
          title: '服务异常',
        })
      }
    })
  },

  /**
   * 重构数组
   */
  addPhotoObject: function(res) {
    var list = [];
    if (res) {
      console.log(res)
      list = this.data.photoList;
      var obj = {
        url: res.tempFilePaths[0]
      }
      list.push(obj)
    } else {
      for (var index in this.data.photoList) {
        let url = this.data.photoList[index]
        var obj = {
          url: url
        }
        list.push(obj)
      }
    }
    console.log(list)
    this.calculateImgHeaght(list);
  },
  /**
   * 计算 图片高度
   */
  calculateImgHeaght: function(photoArray) {
    var width = wx.getSystemInfoSync().windowWidth
    // 一张图片的时候
    var itemImg_width = width - 80 - 36
    // 多张
    if (photoArray.length == (2 - (this.data.isShowAdd ? 0 : 1))) {
      itemImg_width = (width - 20 * 2 - 8 * 2) / 2
    } else if (photoArray.length > (2 - (this.data.isShowAdd ? 0 : 1))) {
      itemImg_width = (width - 20 * 2 - 8 * 3) / 3
    }
    var itemImg_height = itemImg_width / 3 * 4
    console.log(itemImg_width + '   ' + itemImg_height)
    this.setData({
      photoList: photoArray,
      itemImg_height: itemImg_height,
      itemImg_width: itemImg_width,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**     
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  /**
   * 监听 商品描述
   */
  listenerGoodsInput: function(e) {
    this.data.descContent = e.detail.value;
    this.setData({
      descContent: this.data.descContent
    })
  },
  /**
   * 完成 事件 先上传图片数组 
   * 结束以后上传 商品信息
   */
  buttonClick: function() {
    console.log('完成')
    if (this.data.descContent.length < 1) {
      wx.showToast({
        title: '请输入描述',
      })
      return;
    }
    console.log(this.data.descContent)
    var that = this;

    wx.showLoading({
      title: '请稍等',
    })
    var imgUrlArray = []

    for (var index in that.data.photoList) {
      let url = that.data.photoList[index].url
      // 交给七牛上传
      qiniuUploader.upload(url, (res) => {
          console.log(res.imageURL)
          if (res.imageURL) {
            imgUrlArray.push(res.imageURL)
            // 异步 执行完成以后 在上传内容
            if (imgUrlArray.length == that.data.photoList.length) {
              that.releaseGoodsCentent(imgUrlArray);
            }
          } else {
            wx.showModal({
              title: '提示',
              content: '上传图片失败',
            })
          }
        }, (error) => {
          wx.showModal({
            title: '提示',
            content: '上传图片失败',
          })
          console.error('error: ' + JSON.stringify(error));
        }, {
          region: 'ECN', // 华北区
          uptoken: that.data.qntoken,
          domain: 'http://ohc2uub90.bkt.clouddn.com',
          shouldUseQiniuFileName: false
        },
        (progress) => {
          // console.log('上传进度', progress.progress)
          // console.log('已经上传的数据长度', progress.totalBytesSent)
          // console.log('预期需要上传的数据总长度', progress.totalBytesExpectedToSend)
        }
      );
    }
  },

  /**
   * 发布内容
   */
  releaseGoodsCentent: function(array) {
    var that = this;
    wx.getStorage({
      key: 'userLoginToken',
      success(tokenResult) {
        console.log(tokenResult.data)
        wx.request({
          url: 'https://zhj1214.club/upLoad/goodsData',
          // url: 'http://0.0.0.0:8181/upLoad/goodsData',
          method: 'post',
          data: {
            category: "shoes",
            describe: that.data.descContent,
            token: tokenResult.data,
            photoList: array
          },
          success: function (res) {
            console.log('发布 成功')
            console.log(res)
            if (res.data.status == 200){
              wx.showToast({
                title: '发布成功',
              })
              setTimeout(function () {
                wx.navigateBack({
                })
              }, 2000)
            } else {
              wx.showModal({
                title: '抱歉',
                content: '发布失败，请联系小君',
              })
            }
          },
          fail: function () {
            wx.showToast({
              title: '网络异常',
            })
          }
        })
      },
      fail: function(){
        console.log('获取本地 token 缓存失败 ')
        wx.showToast({
          title: 'toek失效，重新登录再试',
        })
      }
    })
  },

  /**
   * 图片点击事件
   */
  photoClick: function(res) {
    var that = this;
    wx.chooseImage({
      success: function(res) {
        if (that.data.photoList == 9) {
          that.data.isShowAdd = true
          that.setData({
            isShowAdd: that.data.isShowAdd
          })
        } else {
          that.data.isShowAdd = false
          that.addPhotoObject(res);
        }
      },
    })
  }
})